package com.sali.config;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.sali.constants.CommonConstant;
import com.sali.disruptor.MessageDisruptorService;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ThreadFactory;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/22 下午2:39.
 * @version: 1.0
 */
@Configuration
@ConfigurationProperties(prefix = "disruptor-config")
@Data
public class DisruptorConfig {

    @Bean
    public MessageDisruptorService getMessageDisruptorService() {
        ThreadFactory threadFactory = ThreadFactoryBuilder.create().setNamePrefix("sali-message-disruptor-").build();
        MessageDisruptorService messageDisruptorService = new MessageDisruptorService(this.getWaitStrategy(), this.getRingBufferSize(), this.getConsumerNum(), threadFactory);
        messageDisruptorService.start();
        return messageDisruptorService;
    }


    private int ringBufferSize;
    private int consumerNum;
    private int waitStrategy;

    public int getRingBufferSize() {
        if (ringBufferSize < CommonConstant.Disruptor.RING_BUFFER_SIZE_MIN || ringBufferSize > CommonConstant.Disruptor.RING_BUFFER_SIZE_MAX) {
            ringBufferSize = CommonConstant.Disruptor.RING_BUFFER_SIZE_MIN;
        }
        return ringBufferSize;
    }

    public int getConsumerNum() {
        if (consumerNum < CommonConstant.Disruptor.CONSUMER_NUM_MIN || consumerNum > CommonConstant.Disruptor.CONSUMER_NUM_MAX) {
            consumerNum = CommonConstant.Disruptor.CONSUMER_NUM_MIN;
        }
        return consumerNum;
    }

    public int getWaitStrategy() {
        if (waitStrategy < CommonConstant.Disruptor.WAIT_STRATEGY_MIN || waitStrategy > CommonConstant.Disruptor.WAIT_STRATEGY_MAX) {
            waitStrategy = CommonConstant.Disruptor.WAIT_STRATEGY_MAX;
        }
        return waitStrategy;
    }
}
